export default class Utils {
    constructor() {
        if (Utils.instance) {
            return Utils.instance;
        }
        Utils.instance = this;
    }

    screen() {
        return { width: document.body.clientWidth, height: document.body.clientHeight }
    }

    deepcopy(obj) {
        return JSON.parse(JSON.stringify(obj));
    }

    xy(screenWidth, screenHeight, dlgWidth, dlgHeight) {
        return  {
            x: (screenWidth <= dlgWidth) ? 0 : (screenWidth - dlgWidth) / 2,
            y: (screenHeight <= dlgHeight) ? 0: (screenHeight - dlgHeight) / 2
        };
    }

    left(val) {
        return (window.screen.width - val) / 2 + 315 + 'px';
    }

    blob(data, filename) {
        const blob = new Blob([data], { type: "application/octet-stream" });
        const link = document.createElement("a");
        link.href = URL.createObjectURL(blob);
        link.download = filename;
        link.click();
        link.remove();
        URL.revokeObjectURL(link.href);
    }

    // 将坐标数组转字符串
    xys2str(coor) {
        let str = '';
        for (let i = 0; i < coor.length; i++) {
            const a = coor[i].join(',');
            str += `[${a}]`;
            if (i < coor.length - 1) {
                str += ',';
            }
        }
        return `[${str}]`;
    }

    // 将字符串转坐标数组
    str2xys(str) {
        if (str.length < 4) { return []; }
        const substr = str.substring(2, str.length - 2);
        const arr = substr.split('],['), coors = [];
        arr.forEach(item => {
            let [x, y] = item.split(',');
            x = parseFloat(x);
            y = parseFloat(y);
            coors.push([x, y]);
        })
        return coors;
    }

    uuid() {
        let s = []
        const hexDigits = "0123456789abcdef"
        for (let i = 0; i < 36; i++) {
            s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
        }
        s[14] = "4";
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1)
        s[8] = s[13] = s[18] = s[23] = "-"
        return s.join("")
    }

    dateOfLocal() {
        const date = new Date();
        const year = date.getFullYear();
        let month = date.getMonth() + 1;
        const day = date.getDate();
        month = month < 10 ? `0${month}` : month;
        return `${year}-${month}-${day}`;
    }

    // 获取localstorage
    getLocalStorage(key) {
        return JSON.parse(window.localStorage.getItem(key));
    }

    // 设置localstorage
    setLocalStorage(key, value) {
        window.localStorage.setItem(key, JSON.stringify(value));
    }

    getUrlParamer(name) {
        const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        const r = window.location.search.substr(1).match(reg);
        if(r !== null) {
            return decodeURI(r[2]);
        }
        return null;
    }

    postMessage(message) {
        window.parent.postMessage(JSON.stringify(message), "*");
    }
}